package com.hotel.writer.lucene.index;

import com.hotel.comm.bean.lucene.IndexableBean;
import com.hotel.writer.lucene.LuceneProp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * �?���?��建索引的Object，都�?��加入到索引仓库中
 * 消费类线程会处理存放在仓库中的Object
 *
 * @author xusemon
 * @date 2015-3-17
 */
public class IndexStore {
    private Logger logger = LoggerFactory.getLogger(IndexStore.class);
    /**
     * 存放IndexBean的Queue
     */
//	private Queue<IndexBean> queue = new LinkedBlockingQueue<IndexBean>();
    private Map<String, Queue<IndexableBean>> queues = new ConcurrentHashMap<String, Queue<IndexableBean>>();

    /**
     * 存放
     *
     * @param indexBean
     * @return
     */
    public boolean put(IndexableBean indexBean) {
        try {
            logger.info("Comming a indexbean, notify all wait threads! IndexBean:" + indexBean.toString());
            Queue<IndexableBean> queue = queues.get(fsPath);
            if (queue == null) {
                queue = new LinkedBlockingQueue<IndexableBean>();
                queues.put(fsPath, queue);
            }
            ((LinkedBlockingQueue<IndexableBean>) queue).put(indexBean);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public IndexableBean remove() {
        try {
            Queue<IndexableBean> queue = queues.get(fsPath);
            if (queue == null) {
                queue = new LinkedBlockingQueue<IndexableBean>();
                queues.put(fsPath, queue);
            }
            return ((LinkedBlockingQueue<IndexableBean>) queue).take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 索引文件存放路径
     */
    private String fsPath;
//	public IndexStore(){}

    /**
     * 构造函数
     *
     * @param fsPath
     */
    public IndexStore(String fsPath) {
        this.fsPath = fsPath;
    }

    public String getFsPath() {
        return fsPath;
    }

    public void setFsPath(String fsPath) {
        this.fsPath = fsPath;
    }

    private static IndexStore positionIndexStore;
    private static IndexStore personIndexStore;

    /**
     * 获取职位信息索引仓库
     *
     * @return
     */
    public synchronized static IndexStore getPositionIndexStore() {
        if (positionIndexStore == null) {
            positionIndexStore = new IndexStore(LuceneProp.POSITIONPATH);
        }
        return positionIndexStore;
    }

    /**
     * 获取个人简历索引仓库
     *
     * @return
     */
    public synchronized static IndexStore getPersonIndexStore() {
        if (personIndexStore == null) {
            personIndexStore = new IndexStore(LuceneProp.PERSONPATH);
        }
        return personIndexStore;
    }
}
